package cn.xclink.kernel.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.xclink.common.mapper.BaseMapper;
import cn.xclink.common.service.BaseService;
import cn.xclink.kernel.entity.Org;
import cn.xclink.kernel.entity.User;
import cn.xclink.kernel.entity.UserOrg;
import cn.xclink.kernel.mapper.OrgMapper;
import cn.xclink.kernel.mapper.UserMapper;
import cn.xclink.kernel.mapper.UserOrgMapper;


@Service
public class OrgService extends BaseService<Org> {

	@Autowired
	private OrgMapper mapper;
	
	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private UserOrgMapper userOrgMapper;
	
	@Override
	public BaseMapper<Org> getMapper() {
		return mapper;
	}
	
	@Override
	public List<Org> find(Org record) {
		//return mapper.selectExt(record);
		return mapper.selectOrg(record);
	}
	
	@Override
	public int delete(Object key) throws Exception {
		Long orgId =  Long.parseLong(key+"");
		//1.校验是否有用户属于该组织，如果有不允许删除
		User user = new User();
		user.setOrgId(orgId);
		List<User> userList = userMapper.select(user);
		if(userList.size() > 0){
			throw new Exception("该组织下已经存在用户，不允许删除！");
		}
		//2.校验是否有用户授权了该组织，如果有不允许删除
		UserOrg uo = new UserOrg();
		uo.setOrgId(orgId);
		if(userOrgMapper.select(uo).size() > 0){
			throw new Exception("该组织已经授权给了用户，不允许删除！");
		}
		//3.校验组织下是否存在子组织，如果存在不允许删除
		Org org = new Org();
		org.setParentId(orgId);
		if(mapper.select(org).size() > 0){
			throw new Exception("该组织下存在子组织，不允许删除！");
		}
		//4.删除用户授权的部门
		//userOrgMapper.delete(uo);
		//5.清空属于该组织的用户的所在组织
//		for(User u : userList){
//			u.setOrgId(null);
//			userMapper.updateByPrimaryKey(u);
//		}
		return super.delete(orgId);
	}

	/**
	 * 查询用户的授权组织
	 * @param userId
	 * @return
	 */
	public List<Org> findOrgByUserId(Long userId){
		return mapper.selectOrgByUserId(userId);
	}
	
	/**
	 * 查询用户的授权组织
	 * @param userId 用户ID
	 * @param ParentIds 父组织Ids
	 * @return
	 */
	public List<Org> findOrgByUserIdAndParentIds(Long userId,String ParentIds){
		return mapper.selectOrgByUserIdAndParentIds(userId,ParentIds);
	}
	
	public Map<String,String> findOrgIdAndName(List<Org> orgList){
		Map<String,String> map = new HashMap<String,String>();
		for(Org org : orgList){
			map.put(org.getOrgId()+"", org.getOrgName());
		}
		return map;
	}
	
	public List<Org> getOrgTree(List<Org> orgList,List<Org> accessOrgList){
		for(Org org : orgList){
			for(Org accessOrg : accessOrgList){
				if(org.getOrgId() == accessOrg.getOrgId()){
					org.setChecked(true);
					break;
				}
			}
		}
		return orgList;
	}
	
	public String[] findOrgIds(List<Org> orgList){
		
		List<String> list = new ArrayList<String>();
		for(Org org : orgList){
			list.add(org.getOrgId()+"");
		}
		return (String[])list.toArray(new String[list.size()]);
	}
}
